<?php


namespace models\Business\Tbk;


use Yaf\Exception;
use Yaf\Registry;

class Tbk
{
    /**
     * 定时采集
     * @return bool
     * @throws \Exception
     */
    static public function getProductByTiming() {
        // redis中读取min_id
        $key = 'tbk:haodanku:min_id';
        $redis = Registry::get('redis');
        $redis->select(0);
        $min_id = $redis->get($key);
        if ($min_id === false)
            $min_id = 1;
        Registry::get('tbk_log')->info("上次采集的min_id是: $min_id");

        list($min_id, $product_arr) = Haodanku::getTbkProductFromHDKByTiming(0, 23, $min_id);
        Registry::get('tbk_log')->info("数据采集完毕。本次采集的min_id: $min_id, 采集到的数据长度: " . count($product_arr));

        if (empty($product_arr)) {
            throw new Exception("数据采集失败", 400);
        }

        $redis->set($key, $min_id);
        $redis->expire($key, strtotime(date('Y-m-d 23:59:59', time())) - time());
        $res = false;
        try {
            TbkProduct::collectTbkProduct($product_arr);
            $res = true;
        } catch (\Exception $e) {
            Registry::get('tbk_log')->err('采集数据写入失败。失败原因: ' . $e->getMessage());
        } finally {
            Registry::get('tbk_log')->info("采集完毕");
            return $res;
        }
    }

}
